package com.daffodil.monitor.util;

import java.util.Map;

import com.alibaba.cloud.nacos.NacosServiceInstance;
import com.daffodil.util.HttpResponseData;
import com.daffodil.util.HttpResponseEntity;
import com.daffodil.util.HttpUtils;
import com.daffodil.util.JacksonUtils;
import com.daffodil.util.StringUtils;

/**
 * -健康指标工具集
 * @author yweijian
 * @date 2022年10月20日
 * @version 2.0.0
 * @description
 */
public class HealthUtils {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static String getHealth(NacosServiceInstance instance) {
        if(StringUtils.isNotNull(instance) && StringUtils.isNotEmpty(instance.getMetadata())) {
            String host = instance.getHost();
            String port = instance.getMetadata().get("management.port");
            String basePath = instance.getMetadata().get("management.endpoints.web.base-path");
            String url = StringUtils.format("http://{}:{}{}/health", host, port, basePath);
            HttpResponseEntity responseEntity = HttpUtils.sendGet(url);
            HttpResponseData response = responseEntity.getData();
            if(StringUtils.isNotEmpty(response.getBody())) {
                Map result = JacksonUtils.toJavaObject(response.getBody(), Map.class);
                return JacksonUtils.getAsString(result, "status");
            }
        }
        return "DOWN";
    }
}
